package com.zy.validate_logon.controller;

import com.zy.validate_logon.bean.User;
import com.zy.validate_logon.quote.Captcha;
import com.zy.validate_logon.quote.GifCaptcha;
import com.zy.validate_logon.quote.SpecCaptcha;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * User: 11473
 * Date: 2019/10/23
 * Time: 10:17
 * Description: 登录的控制器
 */
@Controller
public class UserController {



    @RequestMapping("/userLogin")
    public ModelAndView login(User user,String code,ModelAndView modelAndView,HttpSession session){
        //判断验证码是否相同
        String str = (String) session.getAttribute("code");
        if(str.length() == 4){
            if(!str.equals(code)){
                modelAndView.addObject("msg","错误的验证码");
                modelAndView.setViewName("login");
                return modelAndView;
            }
        }else {
            modelAndView.addObject("msg","验证码初始化错误");
            return modelAndView;
        }
        //判断用户名密码是否相同
        if("admin".equals(user.getUserName()) && "admin".equals(user.getPassWord())){
            modelAndView.addObject("msg","登录成功");
            modelAndView.setViewName("index");
        }else {
            modelAndView.addObject("msg","账号或者密码错误！");
            modelAndView.setViewName("login");
        }
        return modelAndView;
    }

    @RequestMapping("/getGifCode")
    public void getGifCode(HttpSession session, HttpServletResponse response, HttpServletRequest request) throws IOException {

        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/gif");

        //gif的动画验证码 宽 高 位数
        Captcha captcha = new GifCaptcha(146,33,4);
        captcha.out(response.getOutputStream());
        //得到验证码
        String str = captcha.text().toLowerCase();
        session.setAttribute("code",str);

    }

}
